<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="登录地址" prop="ipaddr">
        <el-input
          v-model="queryParams.ipaddr"
          placeholder="请输入登录地址"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="登录状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="登录时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:logininfor:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleClean"
          v-hasPermi="['system:logininfor:remove']"
          >清空</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Unlock"
          :disabled="single"
          @click="handleUnlock"
          v-hasPermi="['system:logininfor:unlock']"
          >解锁</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:logininfor:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="tablesRef"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      :default-sort="defaultSort"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="访问编号" align="center" prop="infoId" />
      <el-table-column
        label="用户名称"
        align="center"
        prop="userName"
        :show-overflow-tooltip="true"
        sortable="custom"
        :sort-orders="['descending', 'ascending']"
      />
      <el-table-column
        label="地址"
        align="center"
        prop="ipaddr"
        width="130"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="登录状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_common_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="msg" :show-overflow-tooltip="true" />
      <el-table-column
        label="访问时间"
        align="center"
        prop="accessTime"
        sortable="custom"
        :sort-orders="['descending', 'ascending']"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.accessTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import * as api from '@/api/system/logininfor'
import { ElForm, ElTable, ElMessage, ElMessageBox } from 'element-plus'
import { useDict } from '@/utils/dict'
import { parseTime } from '@/utils/cj'
import { download } from '@/utils/request/download'

defineOptions({
  name: 'Logininfor',
})

const { sys_common_status } = useDict({
  dicts: ['sys_common_status'],
})

const queryFormRef = ref<InstanceType<typeof ElForm>>()
const tablesRef = ref<InstanceType<typeof ElTable>>()

const loading = ref(true)
const ids = ref<string[]>([])
const single = ref(true)
const multiple = ref(true)
const selectName = ref<string[]>([])
const showSearch = ref(true)
const total = ref(0)
const list = ref([])
const dateRange = ref([])
const defaultSort = reactive<any>({ prop: 'accessTime', order: 'descending' })

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ipaddr: undefined,
  userName: undefined,
  status: undefined,
  orderByColumn: undefined,
  isAsc: undefined,
})

onMounted(() => {
  getList()
})

/** 查询登录日志列表 */
const getList = () => {
  loading.value = true
  api
    .list({
      ...queryParams,
      beginTime: dateRange.value[0],
      endTime: dateRange.value[1],
    })
    .then((response: any) => {
      list.value = response.rows
      total.value = response.total
      loading.value = false
    })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value?.resetFields()
  queryParams.pageNum = 1
  // 重置排序
  if (tablesRef.value) {
    ;(tablesRef.value as any).sort(defaultSort.prop, defaultSort.order)
  }
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.infoId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  selectName.value = selection.map((item) => item.userName)
}

/** 排序触发事件 */
const handleSortChange = (column: any) => {
  queryParams.orderByColumn = column.prop
  queryParams.isAsc = column.order
  getList()
}

/** 删除按钮操作 */
const handleDelete = (row: any) => {
  const infoIds = row.infoId || ids.value
  ElMessageBox.confirm('是否确认删除访问编号为"' + infoIds + '"的数据项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => api.delLogininfor(infoIds))
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

/** 清空按钮操作 */
const handleClean = () => {
  ElMessageBox.confirm('是否确认清空所有登录日志数据项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => api.cleanLogininfor())
    .then(() => {
      getList()
      ElMessage.success('清空成功')
    })
    .catch(() => {})
}

/** 解锁按钮操作 */
const handleUnlock = () => {
  const username = selectName.value
  ElMessageBox.confirm('是否确认解锁用户"' + username + '"数据项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => api.unlockLogininfor(username.join(','))) // todo
    .then(() => {
      ElMessage.success('用户' + username + '解锁成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
const handleExport = () => {
  download(
    'system/logininfor/export',
    {
      ...queryParams,
    },
    `logininfor_${new Date().getTime()}.xlsx`,
  )
}
</script>
